package com.viphuli.app.tool.adapter;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.ButterKnife;

import com.offroader.utils.DateUtils;
import com.offroader.utils.JsonUtils;
import com.offroader.utils.PhoneUtils;
import com.offroader.utils.StringUtils;
import com.offroader.utils.ViewUtils;
import com.viphuli.app.tool.R;
import com.viphuli.app.tool.bean.part.AccountUser;
import com.viphuli.app.tool.bean.part.ArrangeType;
import com.viphuli.app.tool.bean.part.ArrangeView;
import com.viphuli.app.tool.bean.part.ArrangeViewDay;
import com.viphuli.app.tool.common.AccessTokenKeeper;
import com.viphuli.app.tool.common.Constants;
import com.viphuli.app.tool.common.Constants.UserType;
import com.viphuli.app.tool.common.MyApp;
import com.viphuli.app.tool.fragment.ArrangeActionTypeFragment;
import com.viphuli.app.tool.fragment.ArrangeViewFragment;
import com.viphuli.app.tool.fragment.ArrangeViewWeekFragment;
import com.viphuli.app.tool.handler.ArrangeWeekViewResponseHandler.DayUserArrangeHolder;
import com.viphuli.app.tool.utils.ImageUtils;
import com.viphuli.app.tool.utils.OtherUtils;

public class ArrangeWeekViewAdapter extends ArrayAdapter<ArrangeView> implements View.OnClickListener {
	private ArrangeViewWeekFragment caller;
	private List<ArrangeView> list;
	private List<Date> dateList;
	private int[] px;

	private View curCheck;

	public ArrangeWeekViewAdapter(ArrangeViewWeekFragment caller, List<ArrangeView> list, long time) {

		super(caller.getActivity(), R.layout.include_week_view, list);

		this.caller = caller;
		this.list = list;

		Date date = new Date(time);
		dateList = DateUtils.dateToWeek(date);

		px = PhoneUtils.getScreenPix(MyApp.getInstance());
		
		
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public long getItemId(int index) {
		return index;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		ViewHolder holder = null;
		if (convertView == null || convertView.getTag() == null) {
			convertView = ViewUtils.inflateView(MyApp.getInstance(), R.layout.include_week_view);
			holder = new ViewHolder(convertView);
			convertView.setTag(holder);

		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		ArrangeView arrangeView = list.get(position);
		AccountUser user = arrangeView.getUser();//人
		List<ArrangeViewDay> arrangeViewDayList = arrangeView.getArrangeDayList();//一周的排班信息

		for (int i = 0; i < 8; i++) {

			View rowItem = ((ViewGroup) convertView).getChildAt(i);
			
			//每一行内元素的宽度
			ViewGroup.LayoutParams lp = rowItem.getLayoutParams();
			lp.width = px[0] / 8;

			if (i == 0) {//护士名

				TextView rowItemText = ButterKnife.findById(rowItem, R.id.id_view_week_row_item_text);
				rowItemText.setText(user.getUserName());
				
				TextView rowBottomItemText = ButterKnife.findById(rowItem, R.id.id_view_week_row_item_text_bottom);
				
				if(StringUtils.isNotBlank(user.getLeave())){
					rowBottomItemText.setText("余假:"+user.getLeave());
					rowBottomItemText.setVisibility(View.VISIBLE);
				}else{
					rowBottomItemText.setVisibility(View.GONE);
				}
				

				//点击某一天
//				rowItemText.setOnClickListener(this);

			} else {//星期日、星期一、星期二、星期三、星期四、星期五、星期六

				//每天的排班信息
				ArrangeViewDay arrangeViewDay = arrangeViewDayList.get(i - 1);

				Date itemDate = dateList.get(i - 1);

				//每天有多个排班
				List<ArrangeType> arrangeTypeList = arrangeViewDay.getArrangeTypeList();

				long itemTime = OtherUtils.getNeedTime(itemDate.getTime());
				Date itemTimeDate = new Date(itemTime);

				//文本组件
				final View rowItemText = ButterKnife.findById(rowItem, R.id.id_view_week_row_item_text);

				//视图组件绑定数据(某个人的某天排班信息)
				DayUserArrangeHolder dayUserArrangeHolder = new DayUserArrangeHolder(user, arrangeTypeList, itemTimeDate);
				rowItemText.setTag(dayUserArrangeHolder);

				//点击某一天
				rowItemText.setOnClickListener(this);

				//默认选择某个班次（根据人和时间）
				String curUid = user.getUid();
				long curTime = itemTime;

				if (caller.getDefSelectUid().equals(curUid) && DateUtils.isSameDay(curTime, caller.getDefSelectTime())) {
					
					new Handler().postDelayed(new Runnable() {
						
						@Override
						public void run() {
							rowItemText.performClick();
						}
					}, 200);
				}

				ViewGroup rowItemTextLayout = (ViewGroup) rowItemText;
				TextView textOne = (TextView) rowItemTextLayout.getChildAt(0);
				TextView textTwo = (TextView) rowItemTextLayout.getChildAt(1);
				
				ViewGroup vg = (ViewGroup)rowItemTextLayout.getParent();

				//设置排班信息（7天）
				if (arrangeTypeList != null && !arrangeTypeList.isEmpty()) {

					List<String> names = new ArrayList<String>(2);
					List<String> colors = new ArrayList<String>(2);

					for (int j = 0; j < arrangeTypeList.size(); j++) {

						ArrangeType arrangeType = arrangeTypeList.get(j);
						names.add(arrangeType.getName());
						colors.add(arrangeType.getColor());

					}
					
					
					if (arrangeTypeList.size() == 1) {//有一个排班

						textOne.setVisibility(View.VISIBLE);
						textTwo.setVisibility(View.GONE);

						TextView text = (TextView) rowItemTextLayout.getChildAt(0);
						text.setTextColor(Color.parseColor(colors.get(0)));
						text.setText(names.get(0));
						
						vg.getChildAt(1).setVisibility(View.GONE);
						
					} else if (arrangeTypeList.size() == 2) {//有两个排班

						textOne.setVisibility(View.VISIBLE);
						textTwo.setVisibility(View.VISIBLE);

						textOne.setTextColor(Color.parseColor(colors.get(0)));
						textOne.setText(names.get(0));

						textTwo.setTextColor(Color.parseColor(colors.get(1)));
						textTwo.setText(names.get(1));
						
						vg.getChildAt(1).setVisibility(View.VISIBLE);

					} else if (arrangeTypeList.isEmpty()) {//没有排班（清空）

						textOne.setVisibility(View.GONE);
						textTwo.setVisibility(View.GONE);
						
						vg.getChildAt(1).setVisibility(View.GONE);

					}

				} else {//没有排班（清空）

					textOne.setVisibility(View.GONE);
					textTwo.setVisibility(View.GONE);
					
					vg.getChildAt(1).setVisibility(View.GONE);

				}

			}

		}

		return convertView;
	}

	protected class ViewHolder {

		public ViewHolder(View view) {
			ButterKnife.bind(this, view);
		}
	}
	
	@Override
	public void onClick(View view) {
		clickAction(view);
	}
	
	private void clickAction(View view){
		
		Object obj = view.getTag();

		if (ArrangeViewFragment.ACTION_ARRANGE == caller.getActionType()) {//排班操作

			AccessTokenKeeper tokenKeeper = AccessTokenKeeper.readAccessToken(caller.getActivity());

			//非管理员不能点击排班
			if (tokenKeeper.isLogin() && !(tokenKeeper.getUser().getUserType() == UserType.arrange_admin.getValue())) {
				return;
			}

			caller.setType(Constants.ARRANGE_ACTION_TYPE_ARRANGE);//排班

			if (caller.getClickView() != null) {//恢复状态
				caller.getClickView().setBackgroundResource(R.drawable.bg_week_view_day_line);
			}

			if (view instanceof ViewGroup) {
				caller.setClickView((ViewGroup) view);
				caller.getClickView().setBackgroundResource(R.drawable.bg_green_line_bold);
			}

			if (obj != null) {

				//视图绑定的数据
				DayUserArrangeHolder dayUserArrangeHolder = (DayUserArrangeHolder) view.getTag();
				Bundle args = new Bundle();
				args.putString("data", JsonUtils.toJson(dayUserArrangeHolder));

				ArrangeActionTypeFragment arrangeTypeFrag = new ArrangeActionTypeFragment();
				arrangeTypeFrag.setArguments(args);
				arrangeTypeFrag.show(caller.getChildFragmentManager(), arrangeTypeFrag.getClass().getSimpleName());

			}

		} else if (ArrangeViewFragment.ACTION_EXCHANGE == caller.getActionType()) {//替班&换班

			if (obj != null) {

				final DayUserArrangeHolder dayUserArrangeHolder = (DayUserArrangeHolder) view.getTag();

				List<ArrangeType> arrangeTypeList = dayUserArrangeHolder.getArrangeTypeList();
				Date curDate = dayUserArrangeHolder.getDate();

				if (caller.getType() == -1) {//未选择排班或替班
					caller.getDayUserArrangeHolderList().clear();
					caller.getDayUserArrangeHolderList().add(dayUserArrangeHolder);

				} else {

					int size = caller.getDayUserArrangeHolderList().size();
					if (size == 2)
						caller.getDayUserArrangeHolderList().remove(size - 1);
					caller.getDayUserArrangeHolderList().add(dayUserArrangeHolder);

				}

				if (arrangeTypeList != null && !arrangeTypeList.isEmpty()) {

					if (caller.getClickView() != null) {//恢复状态
						caller.getClickView().setBackgroundResource(R.drawable.bg_week_view_day_line);
					}

					caller.setClickView((ViewGroup) view);
					caller.getClickView().setBackgroundResource(R.drawable.bg_green_line_bold);

					if (caller.getType() == -1) {//未选择排班或替班

						caller.getArrangeTypeLayout().setVisibility(View.VISIBLE);
						caller.getExchangeLayout().setVisibility(View.VISIBLE);

						caller.getArrangeBtnExchange().setVisibility(View.VISIBLE);
						caller.getArrangeBtnReplace().setVisibility(View.VISIBLE);
						caller.getArrangeBtnExchangeAction().setVisibility(View.GONE);

						caller.getArrangeTypeLayout().removeAllViews();//移除已有

					} else {//排班或替班

						if (caller.getType() == 3) {//替班

							if (caller.getDayUserArrangeHolderList().size() == 1) {
								caller.getExchangeLayout().setVisibility(View.GONE);
							} else {
								caller.getArrangeTypeLayout().setVisibility(View.VISIBLE);
								caller.getExchangeLayout().setVisibility(View.VISIBLE);

								caller.getArrangeBtnExchange().setVisibility(View.GONE);
								caller.getArrangeBtnReplace().setVisibility(View.GONE);
								caller.getArrangeBtnExchangeAction().setVisibility(View.VISIBLE);

								caller.getArrangeTypeLayout().removeAllViews();//移除已有
							}

						} else if (caller.getType() == 2) {//换班

							if (caller.getDayUserArrangeHolderList().size() == 1) {
								caller.getExchangeLayout().setVisibility(View.GONE);
							} else {
								caller.getArrangeTypeLayout().setVisibility(View.VISIBLE);
								caller.getExchangeLayout().setVisibility(View.VISIBLE);

								caller.getArrangeBtnExchange().setVisibility(View.GONE);
								caller.getArrangeBtnReplace().setVisibility(View.GONE);
								caller.getArrangeBtnExchangeAction().setVisibility(View.VISIBLE);

								caller.getArrangeTypeLayout().removeAllViews();//移除已有
							}

						}

					}

					for (int i = 0; i < arrangeTypeList.size(); i++) {

						View arrangeTypeView = ViewUtils.inflateView(caller.getActivity(), R.layout.include_arrange_type_action);

						View bg = ButterKnife.findById(arrangeTypeView, R.id.id_home_item_icon_bg);
						ImageView img = ButterKnife.findById(arrangeTypeView, R.id.id_home_item_icon_img);
						TextView name = ButterKnife.findById(arrangeTypeView, R.id.id_home_item_icon_name);
						TextView date = ButterKnife.findById(arrangeTypeView, R.id.id_home_item_time);
						TextView duration = ButterKnife.findById(arrangeTypeView, R.id.id_home_item_desc);
						final View check = ButterKnife.findById(arrangeTypeView, R.id.id_home_item_arrange_type_check);

						bg.setBackgroundColor(Color.parseColor(arrangeTypeList.get(i).getColor()));
						ImageUtils.load(img, arrangeTypeList.get(i).getIcon());
						name.setText(arrangeTypeList.get(i).getName());
						date.setText(DateUtils.formatDay(curDate));
						duration.setText(arrangeTypeList.get(i).getDuration());

						//多班时给出选择
						final int index = i;
						if (arrangeTypeList.size() > 1) {

							arrangeTypeView.setOnClickListener(new View.OnClickListener() {

								@Override
								public void onClick(View arg0) {

									if (curCheck != null) {
										curCheck.setBackgroundResource(R.drawable.ic_arrange_type_un_selected);
									}

									curCheck = check;
									curCheck.setBackgroundResource(R.drawable.ic_arrange_type_selected);
									dayUserArrangeHolder.setCheck(index);

								}
							});
						}

						caller.getArrangeTypeLayout().addView(arrangeTypeView);

					}

				} else {

					if (caller.getClickView() != null) {//恢复状态
						caller.getClickView().setBackgroundResource(R.drawable.bg_week_view_day_line);
					}

					caller.setClickView((ViewGroup) view);
					caller.getClickView().setBackgroundResource(R.drawable.bg_green_line_bold);

					caller.getArrangeTypeLayout().setVisibility(View.GONE);
					caller.getExchangeLayout().setVisibility(View.GONE);
					caller.getArrangeBtnExchange().setVisibility(View.GONE);
					caller.getArrangeBtnReplace().setVisibility(View.GONE);
					caller.getArrangeBtnExchangeAction().setVisibility(View.GONE);
				}

			}

		}
		
	}

}
